const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

// 测试配置
const BASE_URL = 'http://localhost:3000';
const TEST_USERNAME = 'testuser';
const TEST_USER_ID = '1';

// 创建测试文件
function createTestFile(filename, content = 'Test file content') {
  const filePath = path.join(__dirname, 'temp', filename);
  
  // 确保temp目录存在
  const tempDir = path.dirname(filePath);
  if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir, { recursive: true });
  }
  
  fs.writeFileSync(filePath, content);
  return filePath;
}

// 清理测试文件
function cleanupTestFile(filePath) {
  if (fs.existsSync(filePath)) {
    fs.unlinkSync(filePath);
  }
}

// 测试单文件上传
async function testSingleFileUpload() {
  console.log('🧪 测试单文件上传...');
  
  const testFilePath = createTestFile('test.txt', 'Hello, this is a test file!');
  
  try {
    const formData = new FormData();
    formData.append('file', fs.createReadStream(testFilePath));
    formData.append('userId', TEST_USER_ID);
    formData.append('name', 'test.txt');
    formData.append('type', 'text/plain');
    formData.append('size', fs.statSync(testFilePath).size.toString());
    formData.append('folderId', '0');
    
    const response = await axios.post(
      `${BASE_URL}/fileUploadDownload/upload/${TEST_USERNAME}`,
      formData,
      {
        headers: {
          ...formData.getHeaders(),
        },
      }
    );
    
    console.log('✅ 单文件上传成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('❌ 单文件上传失败:', error.response?.data || error.message);
    return null;
  } finally {
    cleanupTestFile(testFilePath);
  }
}

// 测试批量文件上传
async function testMultipleFileUpload() {
  console.log('🧪 测试批量文件上传...');
  
  const testFiles = [
    createTestFile('test1.txt', 'Test file 1'),
    createTestFile('test2.txt', 'Test file 2'),
    createTestFile('test3.txt', 'Test file 3')
  ];
  
  try {
    const formData = new FormData();
    
    testFiles.forEach(filePath => {
      formData.append('files', fs.createReadStream(filePath));
    });
    
    formData.append('userId', TEST_USER_ID);
    formData.append('folderId', '0');
    
    const response = await axios.post(
      `${BASE_URL}/fileUploadDownload/upload-multiple/${TEST_USERNAME}`,
      formData,
      {
        headers: {
          ...formData.getHeaders(),
        },
      }
    );
    
    console.log('✅ 批量文件上传成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('❌ 批量文件上传失败:', error.response?.data || error.message);
    return null;
  } finally {
    testFiles.forEach(cleanupTestFile);
  }
}

// 测试获取上传配置
async function testGetUploadConfig() {
  console.log('🧪 测试获取上传配置...');
  
  try {
    const response = await axios.get(`${BASE_URL}/fileUploadDownload/upload-config`);
    console.log('✅ 获取上传配置成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('❌ 获取上传配置失败:', error.response?.data || error.message);
    return null;
  }
}

// 测试不支持的文件类型
async function testUnsupportedFileType() {
  console.log('🧪 测试不支持的文件类型...');
  
  const testFilePath = createTestFile('malicious.exe', 'This is not really an exe file');
  
  try {
    const formData = new FormData();
    formData.append('file', fs.createReadStream(testFilePath));
    formData.append('userId', TEST_USER_ID);
    formData.append('name', 'malicious.exe');
    formData.append('type', 'application/octet-stream');
    formData.append('size', fs.statSync(testFilePath).size.toString());
    formData.append('folderId', '0');
    
    const response = await axios.post(
      `${BASE_URL}/fileUploadDownload/upload/${TEST_USERNAME}`,
      formData,
      {
        headers: {
          ...formData.getHeaders(),
        },
      }
    );
    
    console.log('❌ 应该拒绝不支持的文件类型，但上传成功了:', response.data);
  } catch (error) {
    if (error.response?.status === 400) {
      console.log('✅ 正确拒绝了不支持的文件类型:', error.response.data);
    } else {
      console.error('❌ 意外的错误:', error.response?.data || error.message);
    }
  } finally {
    cleanupTestFile(testFilePath);
  }
}

// 测试文件大小限制
async function testFileSizeLimit() {
  console.log('🧪 测试文件大小限制...');
  
  // 创建一个大文件（模拟超过限制）
  const testFilePath = createTestFile('large.txt', 'x'.repeat(1024 * 1024)); // 1MB文件
  
  try {
    const formData = new FormData();
    formData.append('file', fs.createReadStream(testFilePath));
    formData.append('userId', TEST_USER_ID);
    formData.append('name', 'large.txt');
    formData.append('type', 'text/plain');
    formData.append('size', (200 * 1024 * 1024).toString()); // 声明为200MB
    formData.append('folderId', '0');
    
    const response = await axios.post(
      `${BASE_URL}/fileUploadDownload/upload/${TEST_USERNAME}`,
      formData,
      {
        headers: {
          ...formData.getHeaders(),
        },
      }
    );
    
    console.log('⚠️ 大文件上传结果:', response.data);
  } catch (error) {
    if (error.response?.status === 413) {
      console.log('✅ 正确限制了文件大小:', error.response.data);
    } else {
      console.error('❌ 意外的错误:', error.response?.data || error.message);
    }
  } finally {
    cleanupTestFile(testFilePath);
  }
}

// 运行所有测试
async function runAllTests() {
  console.log('🚀 开始文件上传系统测试...\n');
  
  await testGetUploadConfig();
  console.log('');
  
  await testSingleFileUpload();
  console.log('');
  
  await testMultipleFileUpload();
  console.log('');
  
  await testUnsupportedFileType();
  console.log('');
  
  await testFileSizeLimit();
  console.log('');
  
  console.log('🏁 测试完成！');
  
  // 清理temp目录
  const tempDir = path.join(__dirname, 'temp');
  if (fs.existsSync(tempDir)) {
    fs.rmSync(tempDir, { recursive: true, force: true });
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  runAllTests().catch(console.error);
}

module.exports = {
  testSingleFileUpload,
  testMultipleFileUpload,
  testGetUploadConfig,
  testUnsupportedFileType,
  testFileSizeLimit,
  runAllTests
};
